package com.timothy.service;

import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

import java.net.InetSocketAddress;
import java.net.Socket;

import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;

import com.timothy.answer.BaseAnswer;
import com.timothy.answer.BaseStationSelection;


public class MessageSender {
	
	private static final String LOG_TAG = "MessageSender";
	
	public static String PC_IP;
	public static int PC_PORT = 9999;
	public static String PHONE_IP; 
	
	public static final String Get_Base_Stations = "<Message Type=\"GetBaseStations\">" +
													  "<Content></Content>" +
												   "</Message>";
	
	public static final String Single_Select_Answer = "<Message Type=\"QuestionResult\">" +
														"<Content>" + 
	    													"<SlideIndex>%d</SlideIndex>" +
	    													"<Value>%s</Value>" + 
														"</Content>" + 
													  "</Message>";
    
	public static final String Base_Station_Selection = "<Message Type=\"Authorize\">" +
        													"<Content>" + 
        														"<BaseStation>%s</BaseStation>"+
        														"<Password>%s</Password>"+
        													"</Content>" +
        												"</Message>";
	
	public static final String Multi_Select_Answer = "<Message Type=\"QuestionResult\">"+
														    "<Content>" +
														          "<SlideIndex>%d</SlideIndex>" +
														          "%s" +
														    "</Content>" +
													 "</Message>";
	
	public static final String DISCONNECT = "<Message Type=\"Disconnect\">" + 
    											"<Content>" +
    											"</Content>" +
    										"</Message>";
	
	private static String HEADER = "<Header>" +
	  									"<Phone IPAddress=\"%s\" Name=\"\" Port=\""+PC_PORT+"\"></Phone>" +
	  								"</Header>";
	
	public static String addHeader( String message ) {
		int index = message.indexOf('>')+1;
		return message.substring(0, index) + String.format(HEADER, PHONE_IP) + message.substring(index) ;
	}
	
	/**
	 * retry three times
	 */
	public static boolean sendMessage(String command, int retryTime){
		command = addHeader( command );
		try {
			Socket socket = new Socket();
			socket.connect( new InetSocketAddress(PC_IP, Integer.valueOf(PC_PORT)), 3000 );
			if(!socket.isConnected()){
				return false;
			}
			PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
			out.print(command);
			out.close();
			socket.close();
			return true;
		} catch (Exception ex) {
			if( retryTime<2 )
				return sendMessage(command, ++retryTime );
			return false;
		}
	}
	
	/**
	 * Use eneter to connect server
	 * @param commService
	 * @param command
	 * @param retryTime
	 * @return
	 */
	
/*	static Messenger mService = null;
	public static boolean sendMessage(String command, int retryTime){
		command = addHeader( command );
		
		Log.i(LOG_TAG, "command="+command);
		
		Message msg = Message.obtain(null,CommunicationService.MSG_SEND_SERVER, 0, 0,command);
        try {
			mService.send(msg);
			Log.i(LOG_TAG, "MessengerService.MSG_SEND_SERVER="+CommunicationService.MSG_SEND_SERVER);
			
			return true;
		} catch (RemoteException e) {
			if( retryTime<2 )
				return sendMessage(command, ++retryTime );
			return false;
		}
	}*/
	
	public static boolean sendMessage(String command){
		return sendMessage( command, 0);
	}

	public static boolean sendBaseStationSelection(BaseStationSelection bss) {
		HEADER = HEADER.replaceAll("Name=\"[^\"]*\"", "Name=\""+bss.getUserName()+"\"");
		return sendMessage( bss.toMessage() );
	}
	
	public static boolean sendAnswer( BaseAnswer answer ) {
		String message = answer.toMessage();
		Log.i(LOG_TAG,"sendAnswer:"+message);
		return sendMessage( message ); 
	}
	
	public static boolean sendDisconnectMessage(){
		return sendMessage( DISCONNECT ); 
	}
}
